﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OtherDevice
{
    [Description("LSD测高仪422")]
    class LSDHeightIndicator : LaserBase
    {
        public LSDHeightIndicator(string strName) : base(strName)
        {
            controlFrom = new Form_测高();
        }
        public override bool Get(int n_取值次数, int n_间隔时间, ref double pos)
        {
            lock (Lock)
            {
                try
                {
                    double dSum = 0;
                    for (int i = 0; i < n_取值次数; i++)
                    {
                        if (i != 0)
                            System.Threading.Thread.Sleep(n_间隔时间);
                        string Cmd = "02 4D 45 41 53 55 52 45 20 32 35 35 03";
                        byte[] byteArray = stringToHexByte(Cmd);
                        int ret = SendData(byteArray);
                        byte[] S = new byte[9];
                        ReceiveData(ref S, 3000);
                        string str = System.Text.Encoding.Default.GetString(S);
                        if (str.Contains("\u0002"))
                        {
                            str = str.Replace("\u0002", "");
                        }
                        if (str.Contains("\u0003"))
                        {
                            str = str.Replace("\u0003", "");
                        }
                        dSum += Convert.ToDouble(str);
                    }
                    pos = dSum / (double)n_取值次数;
                    return true;
                }
                catch
                {
                    pos = -1;
                    return false;
                }
            }
        }

        private byte[] stringToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
                
            return returnBytes;
        }
    }
}
